#### Replication Code for:
#### Ministries Matter, Figure 1
#### Author: Erin York
#### Created: 2/3/2023

rm(list = ls())

library(vdemdata)
library(tidyverse)
library(logr)

options("logr.autolog" = TRUE)

# Open the log
lf <- log_open(file.path("logf1.log"))

# Send message to log
log_code()

# generate cab makeup data ------------------------------------------------

## NOTE: this section of code generates the dataset cab_independents.csv using WhoGov data
## WhoGov_within_V2.0
## To generate Figure 1, skip to the next section

# load in whogov individual-level dataset (see readme for access) and set wd to file location
whogov<- read.csv("WhoGov_within_V2.0.csv")

# count number of ministerial posts per countryyear
allmins<- whogov %>%
  filter(classification %in% c("Minister (Junior)", "Minister (Full Rank)")) %>% 
  group_by(country_isocode, year) %>%
  summarise(n_mins= n()) 

# count number of independent ministerial posts per countryyear
ind<- whogov %>% 
  filter(classification %in% c("Minister (Junior)", "Minister (Full Rank)"), 
         party == "independent") %>% 
  group_by(country_isocode, year) %>% summarise(independent = n())

cabdat<- allmins %>% 
  full_join(ind) %>%
  mutate(independent = ifelse(is.na(independent), 0, independent)) %>%
  # generate non-partisan metric
  mutate(prop_ind = independent/n_mins)

# uncomment the below to write cab_independents dataset
#write_csv(x = cabdat, file = "cab_independents.csv")



# generate Figure 1 -------------------------------------------------------

# load in cabinet makeup data
cabdat<- read_csv("cab_independents.csv")
# load vdem data from package
vdem<- vdem

fig1dat<- vdem %>% 
  # remove regime-years where parties are banned altogether
  filter(v2psparban_ord != 1) %>%
  select(country_text_id, year, v2x_regime) %>% 
  rename(country_isocode = country_text_id) %>%
  filter(year >= 1970, year <= 2017) %>%
  # autocracy indicator based on regimes in the world metric
  mutate(Autocracy = ifelse(v2x_regime < 2, "Yes", "No")) %>%
  # merge vdem regimes metric with cabinet data
  right_join(cabdat) %>%
  filter(!is.na(v2x_regime)) %>%
  # generate regime type-year averages
  group_by(Autocracy, year) %>%
  summarise(ind =  mean(prop_ind))

## Figure 1 ##
fig1<- fig1dat %>%
  ggplot(aes(x = year, y = ind, color = Autocracy, shape = Autocracy)) + 
  geom_smooth(se = F, linewidth = .6) +
  geom_point() + 
  theme_bw() +
  ylab("Proportion of Non-Partisan Ministers") +
  xlab("") +
  theme(legend.position = "bottom",
        legend.key.size = unit(1, 'cm'))+
  #  scale_color_viridis_d(begin = .1, end = .6) +
  scale_color_brewer(palette = "Set2") +
  ylim(c(0, NA)) 

ggsave(fig1, filename = "Figure1.pdf",
       width = 8, height = 5)
####

log_close()
